package cn.iocoder.yudao.module.nmkj.dal.redis.useraccess;

import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.module.nmkj.dal.redis.RedisDAOInstance;
import cn.iocoder.yudao.module.nmkj.dal.redis.RedisKeyConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Repository
public class UserAccessRedisDAO implements RedisDAOInstance<Integer> {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final int EFFECTIVE_TIME = 60; //有效时间
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;

    @Override
    public Integer get(String key) {
        String stringValue = stringRedisTemplate.opsForValue().get(formatKey(key));
        return stringValue == null ? 0 : Integer.parseInt(stringValue);
    }

    @Override
    public void set(String key, Integer o) {
        stringRedisTemplate.opsForValue().set(formatKey(key), JsonUtils.toJsonString(o), EFFECTIVE_TIME, TIME_UNIT);
    }

    @Override
    public void delete(String key) {
        stringRedisTemplate.delete(formatKey(key));
    }

    @Override
    public String formatKey(String key) {
        return String.format(RedisKeyConstants.USER_ACCESS, key);
    }

}
